package com.springblog.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.springblog.entity.UserEntity;
import com.springblog.form.LoginForm;
import com.springblog.service.UserService;
import com.springblog.common.utils.JwtUtils;
import com.springblog.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public R login(@RequestBody LoginForm form) {
        if (StringUtils.isBlank(form.getUsername()) && StringUtils.isBlank(form.getPassword())) {
            return R.error("用户名/密码不能为空");
        }
        UserEntity userEntity = userService.getById(1L);

        if (!form.getUsername().equals(userEntity.getUsername()) || !form.getPassword().equals(userEntity.getPassword())) {
            return R.error("用户名或密码不正确");
        }

        String token = jwtUtils.generateToken(1L);
        userEntity.setToken(token);

        // 保存到数据库
        userService.updateById(userEntity);

        return R.ok().put("data", userEntity);
    }

}
